import React, { Component, Suspense } from "react";
import PageHeaderWrapper from "@/components/PageHeaderWrapper";
import { connect } from "dva";
import { routerRedux } from "dva/router";
import PageLoading from "@/components/PageLoading";
import { FormattedMessage } from "umi-plugin-react/locale";
import { Row, Col, Card, Icon, Tooltip, Form, Input, Tree, Button, message, Modal, Spin, Select, TreeSelect } from "antd";
import styles from "./index.less";
import UserSession from "@/UserSession";
import { setFileCategory, editFileCategory, delFileCategory, setUpOrDownFileCategory, getFileCategoryTree, getDocCategoryTree, docCategoryListById } from '@/services/knowledgeFile';
const { TreeNode, DirectoryTree } = Tree;
const FormItem = Form.Item;
const TreeNodes = TreeSelect.TreeNode;
const { confirm } = Modal;
import icon1 from "@/assets/overview/1.png";
import icon2 from "@/assets/overview/2.png";
import icon4 from "@/assets/overview/4.png";
import icon6 from "@/assets/overview/6.png";
import icon7 from "@/assets/overview/7.png";
import chu from "@/assets/overview/chu.png";
import jin from "@/assets/overview/jin.png";
import ReferenceTemplate from './referenceTemplate';
import { TreeShape } from "@/utils/CommonComponent";

class LeftTree extends Component {
    constructor(props) {
        super(props);
        this.state = {
            dataTree: [],
            defaultExpandAll: true,
            selectedKeys: null,
            path: "", // 父节点名称
            disabled: null,
            cid: null,
            title: "",
            loading: false,
            targetRobotId: "",
            open: [],
            openB: [],
            dataTreeB: [],
            selectedKeysB: null,
            pathB: "",
            parentPathB: "",
            cidB: null,
            titleB: "",
            targetRobotIdB: "",
            buttonDJ: false,
            buttonNonew: false,
            qaListCz: "",
            isShared: false,
            parentId: "",
            expandedKeys: [],
            autoExpandParent: true,
            rootNode: "",
            optNode:{},
        };
    }

    componentWillReceiveProps(nextProps, nextContext) {
        if (this.props.onRef) {
            this.props.onRef(this);
        };
        if (nextProps.qaListCz !== this.state.qaListCz) {
            this.setState({ qaListCz: nextProps.qaListCz });
        }
    }

    fetch = (flag) => {
        this.setState({ loading: true },() => {
          const { location: { query }, dispatch, currentUser, categoryId } = this.props;
          // console.log(this.props);
          this.reqRef = requestAnimationFrame(async () => {
              if (!UserSession.isAdmin() && UserSession.isSystemKnowledge()) {
                  let res = await getDocCategoryTree({ libraryId: categoryId });
                  if (res && res[0]) {
                      if (flag === 100) {
                          this.setState({ dataTree: res, loading: false });
                      } else {
                          // 判断展开收起状态
                          const childrenIds = [res[0].id];
                          this.localStorageKeys(childrenIds);
                          // 判断节点选中状态 传入所有分类的节点信息，如果没有储存的节点，则选中所有分类节点
                          let obj = {
                              cid: res[0].id,
                              title: res[0].name,
                              parentId: res[0].parentId,
                              path: res[0].path,
                          };
                          if (query && query.fileCategoryId) {
                              let dataObj = [];
                              function arrData(arr) {
                                  arr.forEach(ele => {
                                      if (ele.children) {
                                          dataObj.push({ ...ele, children: undefined });
                                          arrData(ele.children)
                                      } else {
                                          dataObj.push(ele)
                                      }
                                  });
                              };
                              arrData(res);
                              let objobj = dataObj.filter(item => item.id === query.fileCategoryId) && dataObj.filter(item => item.id === query.fileCategoryId).length > 0 ? dataObj.filter(item => item.id === query.fileCategoryId)[0] : null;
                              obj = objobj ? {
                                  cid: objobj.id,
                                  title: objobj.name,
                                  parentId:objobj.parentId,
                                  path: objobj.path,
                              } : obj;
                              this.localStorageCurrentNode(obj);
                          } else {
                              this.localStorageCurrentNode(obj);
                          };
                          // 记录所有分类的id，用于当默认选中所有分类时，判断分类的操作按钮
                          this.setState({ dataTree: res, loading: false, rootNode: res[0].id });
                      }
                  };
                  this.setState({ loading: false });
              } else {
                  let res = await docCategoryListById({ libraryId: categoryId });
                  if (res && res[0]) {
                    //第一次加载 选中所有分类
                    const { id, parentId, path, name } = res[0];
                    this.props.getListByTreeRoot({ id, path, parentId, title:name });
                    //所有分类下有分类 则加载分类
                    if(res[0].hasChild){
                      const resChildren = await docCategoryListById({libraryId: categoryId,categoryId:res[0].id})
                      res[0].children = resChildren
                    }
                    this.setState({ cid:id, parentId, title:name, path, selectedKeys: id,dataTree: res, loading: false, expandedKeys:[res[0].id] });
                  };
                  this.setState({ loading: false });
              }
          });
        });
       
    };

    /**
     * 处理记忆展开收起状态
     * @param keys
     */
    localStorageKeys = (keys) => {
        // 先判断有没有储存的展开收起 如果没有则展开所有分类节点，如果有，则展开储存的节点
        const treeExpandedKeys = window.localStorage.getItem("treeExpandedFileKeys");
        if (treeExpandedKeys) {
            this.setState({ expandedKeys: treeExpandedKeys.split(",") });
        } else {
            window.localStorage.setItem("treeExpandedFileKeys", keys);
            this.setState({ expandedKeys: keys });
        }
    };

    /**
     * 处理记忆选中节点
     */
    localStorageCurrentNode = (obj) => {
        const { cid, parentId, path, title } = obj;
        this.setState({ cid, parentId, title, path, selectedKeys: cid, });
        // 控制右侧展示知识点
        this.props.getListByTreeRoot({ id: obj.cid, path: obj.path, parentId: obj.parentId, title: obj.title });
    };

    componentWillMount() {
        this.setState({ loading: true });
    }

    componentDidMount() {
        if (this.props.onRef) {
            this.props.onRef(this)
        }
    }

    openedTreeNodes(data) {
        return data.map((item) => {
            let a = this.state.open;
            if (item.children) {
                if (item.data.opened) {
                    a.push(item.id);
                };
                this.openedTreeNodes(item.children);
            };
            this.setState({ open: a });
        });
    }

    onSelect = (selectedKeys, info) => {
        const { location: { pathname }, dispatch } = this.props;
        const { path,disabled,name ,parentId,id} = info.node.props.info

        let cid = selectedKeys[0];
		    dispatch(routerRedux.push({ pathname, query: { fileCategoryId: cid } }));
        if (cid) {
            // 控制菜单一直被选中，不会再次点击取消
            this.setState({ selectedKeys: cid });
            this.setState({ path, disabled, cid, title:name, isShared: false, parentId });
            this.props.terrNodeId(cid, name, path, false, parentId);
        };

        // 如果该节点下有且已加载了子菜单，则触发点击菜单展开收起的方法
        const nodeChildren = info.node.getNodeChildren();
        if (nodeChildren.length > 0) {
          this.onClickToCollapse(info.node.props.eventKey);
        }

        // 选中后存入local Storage
        // console.log(info.node.props);
        const obj = {
            cid:id,
            parentId: parentId,
            title: name,
            path:path,
        };
        window.localStorage.setItem("currentNode", JSON.stringify(obj));
    };

    /**
     * 触发点击菜单展开收起的方法
     * @param cid
     */
    onClickToCollapse = (cid) => {
        let { expandedKeys } = this.state;
        let expandedKeysNew = [];
        if (expandedKeys.indexOf(cid) === -1) {
            expandedKeys.push(cid);
            expandedKeysNew = expandedKeys;
        } else {
            const index = expandedKeys.indexOf(cid);
            expandedKeysNew = expandedKeys.filter((item, i) => i != index);
        };
        this.doExpand(expandedKeysNew);
    };

    reference = () => {
        const { selectedKeys } = this.state;
        if (this.referenceTemplateRef) {
            this.referenceTemplateRef.init({ type: 'classify', id: selectedKeys })
        }
    };

    deleteOk = () => {
        const { dispatch } = this.props;
        const { path, cid,optNode } = this.state;
        this.reqRef = requestAnimationFrame(async () => {
            let res = await delFileCategory({ id: optNode.id });
            // console.log(res);
            if (res.code == 0) {
              message["info"](`${res.message}`);
              // 删除节点后要同步删除存储的节点
              window.localStorage.removeItem("currentNode");
              this.fetch(true);
              this.setState({
                optNode:{}
              })
            }
        });
    };

    upOrDownCategory = (number,item) => {
      this.setState({
        optNode:item
      },() => {
        const {dataTree,optNode } = this.state;
        this.queryParentNode(dataTree, optNode.id, number);
      })
        
    };

    /**
     * 获取当前节点的数据（用于上移下移）
     * @returns {MessageType}
     */
    queryParentNode = (data, currentNodeId, type) => {
        for (const item of data) {
            if (currentNodeId === item.id) {
                this.queryBrotherNode(data, item, type);
            };
            if (item.children) {
                this.queryParentNode(item.children, currentNodeId, type);
            }
        }
    };

    /**
     * 获取当前节点的兄弟节点
     * @returns {MessageType}
     */
    queryBrotherNode = (data, item, type) => {
        let brotherId = null;
        data.map((dataItem, index) => {
            if (dataItem.id === item.id) {
                if (type === 0 && index === 0) {
                    message.error("当前节点已是第一位，无法上移");
                    return false;
                };
                if (type === 1 && index === data.length - 1) {
                    message.error("当前节点已是最后一位，无法下移");
                    return false;
                };
                if (type === 0) {
                    // 上移
                    brotherId = data[index - 1].id;
                };
                if (type === 1) {
                    // 下移
                    brotherId = data[index + 1].id;
                }
            }
        });
        if (brotherId) {
            this.doUpOrDown(brotherId);
        }
    };

    /**
     * 上移下移请求接口
     * @returns {MessageType}
     */
    doUpOrDown = (brotherId) => {
        const { dispatch } = this.props;
        const { optNode } = this.state;
        this.reqRef = requestAnimationFrame(async () => {
            let res = await setUpOrDownFileCategory({ id: optNode.id, targetId: brotherId });
            // console.log(res);
            if (res.code == 0) {
                message["info"](`${res.message}`);
                this.fetch(100);
            }
            this.setState({
              optNode:{}
            })
        });
    };

    /**
     * 分类树展开收起的回调
     */
    doExpand = (expandedKeys, node) => {
      this.setState({ expandedKeys, autoExpandParent: false });
    };

    //设置操作节点
    setOptNode = item => {
      this.setState({optNode:item})
    }

      //新增节点
    addNode = (item,name) => {
      const { dispatch,categoryId } = this.props;
      const { path, parentId } = this.state;
      name = name.replace("_",'')
      this.setState({
        optNode:item
      },() => {
        this.reqRef = requestAnimationFrame(async () => {
          let res = await setFileCategory({ categoryName: name, parentId: item.id, libraryId: categoryId });
          if (res.code == 0) {
              message["info"](`${res.message}`);
              this.fetch();
              const treeExpandedKeys = window.localStorage.getItem("treeExpandedFileKeys");
              if (treeExpandedKeys) {
                  let expandedKeys = treeExpandedKeys.split(",");
                  if (expandedKeys.indexOf(item.id) === -1) {
                      expandedKeys.push(item.id);
                  };
                  window.localStorage.setItem("treeExpandedFileKeys", expandedKeys);
                  this.setState({ expandedKeys });
              }

              this.setState({
                optNode:{},
              })
          }
        });
      })
    }

    //编辑节点名
    nodeUpdateName = async name => {
      const reg = /^[\u4e00-\u9fa5a-zA-Z0-9]+$/g;
      const { dispatch } = this.props;
      const { path,optNode } = this.state;
      if(name.length > 20){
        message.error("支持20位以内大小写字母、数字和中文")
        return false
      }
      if(!reg.test(name)){
        message.error("支持20位以内大小写字母、数字和中文")
        return false
      }
      this.reqRef = requestAnimationFrame(async () => {
        let res = await editFileCategory({ categoryName: name, id: optNode.id });
        if (res.code == 0) {
          message["info"](`${res.message}`);
          // 修改节点后，要同步修改存储的节点信息
          let currentNode = window.localStorage.getItem("currentNode") ? JSON.parse(window.localStorage.getItem("currentNode")) : {};
          currentNode.title = name;
          window.localStorage.setItem("currentNode", JSON.stringify(currentNode));
          this.fetch();
        }
        this.setState({
          optNode:{}
        })
      });
    }

    getChildrenById = async (treeNode,resolve) => {
      const { categoryId } = this.props;
      const res = await docCategoryListById({libraryId: categoryId,categoryId:treeNode.props.eventKey})
      treeNode.props.dataRef.children = res;
      this.setState({
        dataTree: [...this.state.dataTree],
      });
      resolve()
    }

    render() {
        const { expandedKeys, autoExpandParent, selectedKeys, rootNode,optNode,cid } = this.state;
        const { authority, location: { query },authInfo } = this.props;
        //authType：0管理员 1编辑人员 2查看人员 3没有身份
        //0 管理员可操作一切
        //1.身份为编辑人员 根据categoryEditFlag 判断是否可操作
        //2.身份为查看人员 不能编辑
        //3.没有身份的人不能编辑
        const treeDisabled = (authInfo.authType == 1 && !authInfo.categoryEditFlag ) || authInfo.authType == 2 || authInfo.authType == 3

        return (
            <div style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                <ReferenceTemplate onRef={ref => this.referenceTemplateRef = ref} />
                <Spin className={styles.spin} spinning={this.state.loading}>
                    {this.state.dataTree.length === 0 ? null : (
                      <TreeShape treeData={this.state.dataTree} 
                        optNode={optNode}
                        currentNode={{id:cid}}
                        expandedKeys={expandedKeys}
                        nodeSelect={this.onSelect}
                        addNode={this.addNode}
                        nodeExpand={this.doExpand}
                        nodeDelete={this.deleteOk}
                        setOptNode={this.setOptNode}
                        nodeUpdateName={this.nodeUpdateName}
                        nodeMove={this.upOrDownCategory}
                        deleteDisabled={treeDisabled}
                        moveDisabled={treeDisabled}
                        addDisabled={treeDisabled}
                        editDisabled={treeDisabled}
                        getCategoryChildren={this.getChildrenById}
                      />
                    )}
                </Spin>
            </div>
        );
    }
}

export default connect(({ user }) => ({
    currentUser: user.currentUser,
}))(Form.create()(LeftTree));
